﻿using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using ImoviesBlazorAntPro.Shared.Utils;
using ImoviesBlazorAntPro.Shared.Dtos;

namespace ImoviesBlazorAntPro.Client.Pages
{
    public partial class SearchResult
    {
        [Inject]
        HttpClient HttpClient { get; set; }


        [Parameter]
        [SupplyParameterFromQuery]
        public string? Type { get; set; }

        [Parameter]
        [SupplyParameterFromQuery]
        public string? Keyword { get; set; }


        class VideoDto
        {
            public string Id { get; set; } = string.Empty;
            public string Name { get; set; } = string.Empty;
            public string Url { get; set; } = string.Empty;
            public string Category { get; set; } = string.Empty;
            public string Region { get; set; } = string.Empty;
            public uint Year { get; set; }
            public string Actors { get; set; } = string.Empty;
            public string Director { get; set; } = string.Empty;
            public string Intro { get; set; } = string.Empty;
            public string Img { get; set; } = string.Empty;
            public string Comment { get; set; } = string.Empty;
        }

        class VlinkDto
        {
            public uint Id { get; set; }
            public string Name { get; set; } = string.Empty;
            public string Url { get; set; } = string.Empty;
            public string RealUrl { get; set; } = string.Empty;
        }

        // 视频列表数据
        private List<VideoDto> _dataList = new List<VideoDto>();
        // 视频播放链接缓存
        private Dictionary<string, List<VlinkDto>> _vlinkCache = new Dictionary<string, List<VlinkDto>>();


        // 播放器是否显示
        private bool _playerIsVisible = false;
        // 真实播放地址
        private string _realPlayUrl = string.Empty;
        // 当前视频名称
        private string _currentVideo = string.Empty;
        // 播放器标题
        private string _playerTitle = string.Empty;
        // 暂存前一次展开链接列表的视频id
        private string _oldVideoId = string.Empty;
        // 暂存前一次需解析视频地址
        private string _oldOriginPlayUrl = string.Empty;


        /// <summary>
        /// 加载完毕事件
        /// </summary>
        /// <returns></returns>
        protected override async Task OnInitializedAsync()
        {
            //await base.OnInitializedAsync();

            HttpResponseMessage resp;
            switch (Type)
            {
                case "1":
                    // 获取视频列表
                    resp = await HttpClient.GetAsync($"/api/teleplay/search?keyword={Keyword}");
                    break;
                case "2":
                    // 获取视频列表
                    resp = await HttpClient.GetAsync($"/api/movie/search?keyword={Keyword}");
                    break;
                case "3":
                    // 获取视频列表
                    resp = await HttpClient.GetAsync($"/api/animation/search?keyword={Keyword}");
                    break;
                default:
                    return;
            }
            _dataList = JsonSerializer.Deserialize<List<VideoDto>>(await resp.Content.ReadAsStringAsync(),
                new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true,
                    IncludeFields = true,
                });

        }



        /// <summary>
        /// 通过id获取视频链接列表
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task GetVlinksById(string id)
        {
            if (_vlinkCache.ContainsKey(id))
            {
                return;
            }
            HttpResponseMessage resp = null;
            switch (Type)
            {
                case "1":
                    // 获取视频播放链接
                    resp = await HttpClient.GetAsync($"/api/teleplay/vlist/{id}");
                    break;
                case "2":
                    // 获取视频播放链接
                    resp = await HttpClient.GetAsync($"/api/movie/vlist/{id}");
                    break;
                case "3":
                    // 获取视频播放链接
                    resp = await HttpClient.GetAsync($"/api/animation/vlist/{id}");
                    break;
                default:
                    return;
            }

            var list = JsonSerializer.Deserialize<List<VlinkDto>>(await resp?.Content.ReadAsStringAsync(),
            new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true,
                IncludeFields = true,
            });
            if (list != null || list.Count > 0)
            {
                _vlinkCache.Add(id, list);
            }
        }


        /// <summary>
        /// 获取真实播放地址
        /// </summary>
        /// <param name="url">原url</param>
        public async Task GetRealPlayLink(string name, string url)
        {
            // 真实播放地址为空或需解析地址不等于上次地址时才进行请求
            if (string.IsNullOrEmpty(_realPlayUrl) || url != _oldOriginPlayUrl)
            {
                string cate = string.Empty;
                switch (Type)
                {
                    case "1":
                        cate = "Teleplay";
                        break;
                    case "2":
                        cate = "Movie";
                        break;
                    case "3":
                        cate = "Animation";
                        break;
                    default:
                        return;
                }
                // 真实地址解析
                var resp = await HttpClient.PostAsJsonAsync<LinkParseReqParameter>("/api/playlink",
                    new LinkParseReqParameter { Vcate = cate, OriginUrl = url });
                _realPlayUrl = await resp.Content.ReadAsStringAsync();
                _oldOriginPlayUrl = url;
            }
            _playerTitle = $"正在播放 「{_currentVideo}-{name}」";
            _playerIsVisible = true;
        }


        /// <summary>
        /// 播放器关闭
        /// </summary>
        public void PlayerClose()
        {
            _realPlayUrl = string.Empty;
            _playerTitle = string.Empty;
            _playerIsVisible = false;
        }


    }
}
